import React, { PureComponent, createRef } from 'react'

class Counter extends PureComponent {
  constructor() {
    super()

    this.state = {
      counter: 0
    }
  }

  render() {
    return (
      <div>
        <h2>{this.state.counter}</h2>
        <button onClick={e => this.increment()}>-1</button>
        <button onClick={e => this.decrement()}>-1</button>
      </div>
    )
  }

  increment () {
    this.setState({
      counter: this.state.counter + 1
    })
  }

  decrement() {
    this.setState({
      counter: this.state.counter - 1
    })
  }
}

export default class App extends PureComponent {
  constructor(props) {
    super(props)

    this.titleRef = createRef()
    this.titleEl = null
    this.counterRef = createRef()
  }
  render() {
    return (
      <div>
        {/* <h2 ref=字符串/对象/函数>Hello Hello</h2> */}
        <h2 ref="titleRef">Hello Hello</h2>
        {/* 目前React推荐方式 */}
        <h2 ref={this.titleRef}>Hello Hello</h2>
        {/* 函数方式 */}
        <h2 ref={arg => this.titleEl = arg}>Hello Hello</h2>
        <hr />
        <button onClick={e => this.changeText()}>Change Text</button>
        <Counter ref={this.counterRef} />
        <button onClick={e => this.appBtnClick()}>App Button</button>
      </div>
    )
  }

  changeText() {
    // 使用方式一: 字符串
    this.refs.titleRef.innerHTML = 'Hello React'
    // 使用方式二： 对象
    this.titleRef.current.innerHTML = 'Hello React'
    // 使用方式三：函数
    this.titleEl.innerHTML = 'Hello React'
  }

  appBtnClick() {
    this.counterRef.current.increment()
  }

}

